<?php

namespace app\user\model;

use think\Model;
use Carbon\Carbon;
use app\common\traits\model\TraitModel;

/**
 * 会员模块旅行币模型
 */
class Intergrates extends Model
{

    protected $table = 'integral_detail';
    const INTEGRAL_TO_MONEY_RATE = 0.5;
    const CURRENCYS =  'USD,CNY';
    //protected static $loginuser = '';
    
    use TraitModel;

    //增加积分

    public function addIntergrates($intergrate, $user_id = null, $option = [])
    {
        $option = array_merge(['type' => '收入', 'remark' => '收入'], $option);
        return $this->intergrateOperation(abs($intergrate), $user_id, $option, false);
    }

    //减少积分
    public function reduceIntergrates($intergrate, $user_id = null, $option = [], $abs = true)
    {
        $option = array_merge(['type' => '消费', 'remark' => '消费'], $option);
        return $this->intergrateOperation((0 - abs($intergrate)), $user_id, $option, $abs);
    }
    /**
     * 积分操作
     * @param  [type] $intergrate [description]
     * @param  [type] $user_id    [description]
     * @param  string $type       [description]
     * @param  [type] $remark     [description]
     * @return [type]             [description]
     */
    protected function intergrateOperation($intergrate, $user_id = null, $option = [], $abs)
    {
        if ($user_id) {
            $user = model('user/Users')->get($user_id);
        }else{
            $user = self::getLoginUserInfo();
        }

        if (!$user) {
            throw new \Exception("user is null", 1);
            
        }
        
        if ((int)$intergrate < 0 && $abs === true) {
            if ($user->integral < abs($intergrate)) {
                throw new \Exception("Deficiency of integral", -89);
            }
        }
        $user->integral = $user->integral + $intergrate;
        $user->save();
        $user_id = $user->id;
        $user_mobile = $user->mobile;
        $camp_id = $user->camp_id;
        $branch_id = model('user/Camps')->where('id',$camp_id)->value('branch_id');
        $logs = ['user_id' => $user_id, 'user_mobile' =>$user_mobile, 'type' => $option['type'], 'intergrate' => abs($intergrate), 'remark' => $option['remark'], 'camp_id' => $camp_id, 'branch_id' => $branch_id];
        $this->createIntergrateLogs($logs);
    }

    //积分流水,写入日志
    private function createIntergrateLogs($intergrate_info)
    {
        return self::create($intergrate_info, true);
    }

    public function getCurrency($to = 'USD')
    {
       return $to != 'CNY' ? model('Currency')->getCurrency($to) : 1;
    }

    public function getIntergratesLists($query = array(), $order = 'updated_at desc')
    {
        return $this->getInfoList(array_merge($query, ['user_id' => self::getLoginUserInfo('id')]), $order = 'created_at desc');
    }
    public function getIncomeIntergratesLists($query = array(), $order = 'updated_at desc')
    {
        return $this->getInfoList(array_merge($query, ['user_id' => self::getLoginUserInfo('id'), 'type' => '收入']), $order = 'created_at desc');
    }
    public function getSpendIntergratesLists($query = array(), $order = 'updated_at desc')
    {
        return $this->getInfoList(array_merge($query, ['user_id' => self::getLoginUserInfo('id'), 'type' => '消费']), $order = 'created_at desc');
    }
    /**
     * 获取登录用户积分
     * @return [type] [description]
     */
    public function getUserIntegral()
    {
        return self::getLoginUserInfo('integral');
    }

    /**
     * 积分转金钱
     * @author sanyc <9714928@qq.com>
     * @param  [type] $integral [description]
     * @return [type]        [description]
     */
    public function integralToMoney($integral, $to = 'USD')
    {
        $currency = $this->getCurrency($to);
        if (!$currency) {
            throw new \Exception("Currency error", -87);
        }
        $integralToMoneyRate = $this->getIntegralToMoneyRate();//halt($integralToMoneyRate);
        $c = $integral * $integralToMoneyRate;//人民币
        return $c * $currency;
    }
    /**
     * 计算差价
     * @author sanyc <9714928@qq.com>
     * @param  string $value [description]
     * @return [type]        [description]
     */
    public function difference($userIntegral, $intergrate, $to = 'intergrate')
    {
        //$userIntegral = $this->getUserIntegral($user_id);
        if ($to != 'intergrate' && in_array($to, explode(',', self::CURRENCYS))) {
            return $userIntegral >= $intergrate ? 0 : $this->integralToMoney($intergrate - $userIntegral, $to);
        }
        return $userIntegral >= $intergrate ? 0 : $intergrate - $userIntegral;
    }
    /**
     * 积分转人民币比率
     */
    private function getIntegralToMoneyRate()
    {
        if ($integral_to_money_rate = self::getSettings('systems.rate')) {
            return $integral_to_money_rate;
        }
        return self::INTEGRAL_TO_MONEY_RATE;
    }
    /**
     * 货币转换
     * @param  [type] $money [description]
     * @param  [type] $from  [description]
     * @param  string $to    [description]
     * @return [type]        [description]
     */
    public function moneyTrans($money, $from, $to = 'USD')
    {
        if ($from == $to) {
            return $money;
        }
        $currency = model('Currency')->getCurrency($to, $from);
        return number_format($money * $currency, 2, '.', '');
    }


    
}
